/**
 * 拖拽管理模块
 * 负责处理元素库到画布的拖拽功能
 */
class DragDropManager {
    constructor(canvas, elementManager) {
        this.canvas = canvas;
        this.elementManager = elementManager;
        this.setupDragAndDrop();
    }

    /**
     * 设置拖拽功能
     */
    setupDragAndDrop() {
        // 设置元素库中的可拖拽元素
        const elementItems = document.querySelectorAll('.element-item');
        elementItems.forEach(item => {
            item.draggable = true;
            item.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', item.getAttribute('data-type'));
                e.dataTransfer.effectAllowed = 'copy';
            });
        });

        // 使用事件委托，监听Swiper容器或整个canvas-wrapper
        const canvasWrapper = document.querySelector('.canvasSwiper') || document.querySelector('.canvas-wrapper');
        
        if (canvasWrapper) {
            canvasWrapper.addEventListener('dragover', (e) => {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy';
            });

            canvasWrapper.addEventListener('drop', (e) => {
                e.preventDefault();
                const elementType = e.dataTransfer.getData('text/plain');
                if (elementType) {
                    // 找到实际的canvas元素
                    const targetCanvas = e.target.closest('.canvas') || document.querySelector('.canvas[data-page="' + (window.pageBuilder ? window.pageBuilder.currentPageIndex : 0) + '"]');
                    
                    if (targetCanvas) {
                        // 更新ElementManager的canvas引用到目标canvas
                        this.canvas = targetCanvas;
                        this.elementManager.canvas = targetCanvas;
                        
                        // 同时更新PageBuilder的canvas引用
                        if (window.pageBuilder) {
                            window.pageBuilder.canvas = targetCanvas;
                        }
                        
                        const rect = targetCanvas.getBoundingClientRect();
                        const x = e.clientX - rect.left - 2;
                        const y = e.clientY - rect.top - 2;
                        
                        // 检查是否拖拽到网格中
                        const gridContent = e.target.closest('.grid-content');
                        if (gridContent) {
                            const gridId = gridContent.getAttribute('data-grid-id');
                            this.elementManager.addElementToGrid(elementType, gridId);
                        } else {
                            const element = this.elementManager.createElement(elementType, x, y);
                            this.elementManager.renderElement(element);
                            // 自动选择新创建的元素
                            this.elementManager.selectElement(element);
                        }
                    }
                }
            });
        } else {
            // 降级方案：直接监听canvas
            this.canvas.addEventListener('dragover', (e) => {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy';
            });

            this.canvas.addEventListener('drop', (e) => {
                e.preventDefault();
                const elementType = e.dataTransfer.getData('text/plain');
                if (elementType) {
                    const rect = this.canvas.getBoundingClientRect();
                    const x = e.clientX - rect.left - 2;
                    const y = e.clientY - rect.top - 2;
                    
                    // 检查是否拖拽到网格中
                    const gridContent = e.target.closest('.grid-content');
                    if (gridContent) {
                        const gridId = gridContent.getAttribute('data-grid-id');
                        this.elementManager.addElementToGrid(elementType, gridId);
                    } else {
                        const element = this.elementManager.createElement(elementType, x, y);
                        this.elementManager.renderElement(element);
                        // 自动选择新创建的元素
                        this.elementManager.selectElement(element);
                    }
                }
            });
        }
    }

    /**
     * 重新设置拖拽功能（用于动态添加的元素）
     */
    refreshDragAndDrop() {
        const elementItems = document.querySelectorAll('.element-item');
        elementItems.forEach(item => {
            item.draggable = true;
            item.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', item.getAttribute('data-type'));
                e.dataTransfer.effectAllowed = 'copy';
            });
        });
    }
}

// 导出类（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = DragDropManager;
}
